package com.dlwx.parttimetalent.views;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;

/**
 * Created by Administrator on 2017/11/23.
 */

public class SingleSeekBar extends View {

    private int viewWidth;
    private int viewHeight = 50;
    private int bgHeight = 12;
    private int thumbHeight = 20;
    private int thumbWidth = 14;
    private static final int mTop = 10;
    private RectF bgRectF;
    private int mLeft;
    private int thumbRightLeft;
    private int textLeft;
    private int downX;
    private int mType = ThumbType.THUMB_LEFT;
    private int range = 100;
    //刻度
    private int mGraduation;


    public SingleSeekBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SingleSeekBar(Context context) {
        this(context, null);
    }

    public SingleSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int measureHeight;
        if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            measureHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, viewHeight, getContext().getResources().getDisplayMetrics());
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(measureHeight, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        this.viewWidth = w;
        this.viewHeight = h;
        mLeft = mTop;
        thumbRightLeft = 4 * mLeft;
        mGraduation = viewWidth / range;
        bgRectF = new RectF(0, mTop, viewWidth, bgHeight + mTop);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawRoundBg(canvas);
        drawLeftThumb(canvas);
        drawRightThumb(canvas);
        drawProgressBg(canvas);
        drawText(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        //最好判定下版本,低版本无此API
        int masked = event.getActionMasked();
        switch (action & masked) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) event.getRawX();
                mType = judgeIsLeftOrRightThumb(downX);
                break;
            case MotionEvent.ACTION_MOVE:
                actionOperations((int) event.getRawX());
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                actionOperations((int) event.getRawX());
                break;
        }
        return true;
    }

    private void drawRoundBg(Canvas canvas) {
        Paint paint = initPaint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.LTGRAY);
        canvas.drawRect(bgRectF, paint);
    }

    private void drawLeftThumb(Canvas canvas) {
        Paint paint = initPaint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        RectF leftThumbF = new RectF(mLeft, mTop + bgHeight / 2 - thumbHeight / 2, thumbWidth + mLeft, mTop + bgHeight / 2 + thumbHeight / 2);
        canvas.drawRoundRect(leftThumbF, 5, 5, paint);
    }

    private void drawRightThumb(Canvas canvas) {
        Paint paint = initPaint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        RectF rightThumbF = new RectF(thumbRightLeft, mTop + bgHeight / 2 - thumbHeight / 2, thumbWidth + thumbRightLeft, mTop + bgHeight / 2 + thumbHeight / 2);
        canvas.drawRoundRect(rightThumbF, 5, 5, paint);
    }

    private void drawProgressBg(Canvas canvas) {
        Paint paint = initPaint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLUE);
        RectF progressF = new RectF(mLeft + thumbWidth, mTop, thumbRightLeft, bgHeight + mTop);
        canvas.drawRect(progressF, paint);
    }

    private void drawText(Canvas canvas) {
        String text = getmGraduation()[0] + "--" + getmGraduation()[1];
        Paint paint = initPaint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(20.F);
        int textLength = (int) paint.measureText(text);
        textLeft = ((thumbRightLeft - mLeft) - textLength) / 2 + mLeft;
        if (textLeft >= getWidth() - textLength) {
            textLeft = getWidth() - textLength;
        } else if (textLeft <= 0) {
            textLeft = 0;
        }
        canvas.drawText(text, textLeft, 5 * mTop, paint);
    }

    private Paint initPaint() {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(1.F);
        paint.setShader(null);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        return paint;
    }

    private int judgeIsLeftOrRightThumb(int x) {
        return Math.abs(mLeft - x) - Math.abs(thumbRightLeft - x) > 0 ? ThumbType.THUMB_RIGHT : ThumbType.THUMB_LEFT;
    }

    private void actionOperations(int acionX) {
        if (mType == ThumbType.THUMB_LEFT) {
            if (acionX <= thumbWidth / 2) {
                mLeft = 0;
            } else if (acionX >= thumbRightLeft - thumbWidth / 2) {
                mLeft = thumbRightLeft - thumbWidth / 2;
            } else {
                mLeft = acionX;
            }
        } else if (mType == ThumbType.THUMB_RIGHT) {
            if (acionX <= thumbWidth / 2 + thumbWidth) {
                thumbRightLeft = 0;
            } else if (acionX >= getWidth() - thumbWidth) {
                thumbRightLeft = getWidth() - thumbWidth;
            } else {
                if(thumbRightLeft <= mLeft){
                    mType = ThumbType.THUMB_LEFT;
                    return;
                }
                thumbRightLeft = acionX;
            }
        }
        invalidateView();
    }

    private void invalidateView() {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            invalidate();
        } else {
            postInvalidate();
        }
    }

    private void startAnimation(final int x1, final int x2) {
        //android 3.0后才有属性动画ObjectAnimation,3.0以下版本使用Nineoldandroid.jar使用属性动画
        ValueAnimator valueAnimator = ObjectAnimator.ofFloat(x1, x2);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.setDuration(200);
        valueAnimator.setRepeatCount(0);
        valueAnimator.setStartDelay(200);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                Float atFloat = (Float) valueAnimator.getAnimatedValue();
                if (x2 >= x1) {
                    if (mType == ThumbType.THUMB_LEFT) {
                        mLeft = (int) (mLeft * atFloat);
                    } else if (mType == ThumbType.THUMB_RIGHT) {
                        thumbRightLeft = (int) (thumbRightLeft * atFloat);
                    }
                } else {
                    if (mType == ThumbType.THUMB_LEFT) {
                        mLeft = (int) (mLeft * (1 - atFloat));
                    } else if (mType == ThumbType.THUMB_RIGHT) {
                        thumbRightLeft = (int) (thumbRightLeft * (1 - atFloat));
                    }
                }
                invalidateView();
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        valueAnimator.start();
    }

    private int[] getmGraduation() {
        int[] graduations = new int[2];
        int leftRange = mLeft / mGraduation;
        int rightRange = thumbRightLeft / mGraduation;
        if (leftRange <= 0) {
            leftRange = 0;
        }
        if (rightRange >= 100) {
            rightRange = 100;
        }
        graduations[0] = leftRange;
        graduations[1] = rightRange;
        Log.e(getClass().getSimpleName(), graduations[0] + "----" + graduations[1]);
        return graduations;
    }

    private static class ThumbType {
        private static final int THUMB_LEFT = 0;
        private static final int THUMB_RIGHT = 1;
    }
}
